import { Injectable, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from '../../../common/decorators/public.decorator';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private reflector: Reflector) {
    super();
  }

  canActivate(context: ExecutionContext) {
    // 检查是否标记为公共接口
    const isPublic = this.reflector.getAllAndOverride<boolean>(
      IS_PUBLIC_KEY,
      [context.getHandler(), context.getClass()],
    );

    // 如果是公共接口，则跳过认证
    if (isPublic) {
      return true;
    }

    // 获取请求对象
    const request = context.switchToHttp().getRequest();
    console.log('JWT验证 - 请求路径:', request.url);
    console.log('JWT验证 - Authorization头:', request.headers.authorization);

    return super.canActivate(context);
  }

  handleRequest(err: any, user: any, info: any) {
    // 记录详细的验证信息
    console.log('JWT验证结果 - 错误:', err);
    console.log('JWT验证结果 - 用户:', user);
    console.log('JWT验证结果 - 信息:', info);

    // 如果有错误或者没有用户，抛出未认证异常
    if (err || !user) {
      if (info && info.message) {
        // 提供更详细的错误信息
        if (info.name === 'TokenExpiredError') {
          throw new UnauthorizedException('Token已过期，请重新登录');
        } else if (info.name === 'JsonWebTokenError') {
          throw new UnauthorizedException('无效的Token');
        }
      }
      throw err || new UnauthorizedException('身份验证失败，请重新登录');
    }
    return user;
  }
} 